from fastapi import Request, HTTPException

from app.config.settings import settings  # 已存在的导入
from app.core.local_logging import setup_logging
from app.core.encryption_utils import cipher

logger = setup_logging()

# 入参验证中间件
async def validate_request_params(request: Request, call_next):
    """
    验证请求参数的中间件（支持全局配置控制是否解密）
    :param request: 请求对象
    :param call_next: 下一个中间件或路由处理函数
    :return:
    """
    if request.url.path in settings.DOC_PATHS:
        return await call_next(request)

    logger.debug(f"[请求处理] [原始数据]: {await request.body()}")

    # 提取公共解密逻辑为函数
    async def decrypt_request_body(body: bytes) -> bytes:
        if settings.API_DECRYPT_ENABLED:
            try:
                decrypted = cipher.decrypt(body.decode())
                logger.debug("已启用解密，请求体已解密")
                return decrypted.encode()
            except Exception as e:
                logger.error(f"解密请求体失败: {e}")
                raise HTTPException(status_code=400, detail="解密请求体失败")
        return body

    if request.method in ["POST", "PUT"]:
        content_type = request.headers.get("content-type")
        if not content_type or "application/json" not in content_type:
            raise HTTPException(status_code=400, detail="Content-Type must be application/json")
        
        body = await request.body()
        if body and settings.API_DECRYPT:
            request._body = await decrypt_request_body(body)

    # 注意：GET 请求通常没有请求体，建议仅处理查询参数中的加密值（若有）
    elif request.method == "GET":
        logger.debug(f"validate GET Received request: {request.method} {request.url}")
        logger.debug(f"validate GET Received request: {request.query_params}")
        body = request.query_params
        if not body:
            logger.warning(f"no body")
        if settings.API_DECRYPT:
            # 修正：使用 str() 转换 QueryParams 为字符串
            query_str = str(request.query_params)  # 替换原有的 toString() 调用
            try:
                decrypted_query = cipher.decrypt(query_str)
                # 此处根据业务需求处理解密后的查询参数（示例为记录）
                logger.debug(f"解密后的查询参数: {decrypted_query}")
            except Exception as e:
                logger.error(f"解密查询参数失败: {e}")
                raise HTTPException(status_code=400, detail="解密查询参数失败")

    return await call_next(request)